package edu.tgc.web.controller.teaching;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.abyss.common.web.controller.easyui.CommonCrudEasyUiController;
import org.abyss.common.web.controller.easyui.EasyuiAjaxFormResult;
import org.abyss.common.web.controller.easyui.EasyuiResultBuilder;
import org.abyss.data.specifications.Rule;
import org.apache.commons.codec.binary.Base64;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import edu.tgc.entity.student.TbClass;
import edu.tgc.entity.system.SysUser;
import edu.tgc.entity.teaching.Enroll;
import edu.tgc.entity.teaching.TbParticipant;
import edu.tgc.security.SessionUserUtils;
import edu.tgc.service.teaching.EnrollService;
import edu.tgc.service.teaching.ParticipantService;
import edu.tgc.web.form.teaching.ParticipantForm;

@Controller
@RequestMapping(value="/teaching/participant")
public class ParticipantController extends CommonCrudEasyUiController<TbParticipant, UUID, ParticipantForm> {
	@Autowired
	private ParticipantService service;
	@Autowired
	private EnrollService enrollService;
	@Override
	public EasyuiAjaxFormResult create(ParticipantForm form, BindingResult bindingResult, Model model,
			RedirectAttributes redirectAttributes) {
		try{
			TbParticipant participant=new TbParticipant();
			BeanUtils.copyProperties(form, participant);
			baseService.save(participant);
			return EasyuiResultBuilder.buildAjaxResult("新增记录成功");
		}catch (Exception e) {
			return EasyuiResultBuilder.buildAjaxResultError("新增记录失败");
		}
	}

	
	@Override
	public EasyuiAjaxFormResult delete(ParticipantForm form, BindingResult bindingResult, Model model,
			RedirectAttributes redirectAttributes) {
		try {
			UUID id = form.getId();
			service.delete1(id);
			return EasyuiResultBuilder.buildAjaxResult("删除记录成功");
		} catch (Exception e) {
			return EasyuiResultBuilder.buildAjaxResultError("删除记录失败");
		}
	}


	@Override
	public Specification<TbParticipant> buildSearch(ParticipantForm form) {
		Date now=new Date();
		HashSet<Rule> rules=new HashSet<>();
		SysUser user= SessionUserUtils.getSysUser();
		UUID id=null;
		if(user!=null){
			id=user.getId();
			rules.add(Rule.property("creator.id").equal(id));
		}else{
			rules.add(Rule.property("creator").isNull());
		}
		rules.add(Rule.property("enroll.endTime").greaterThan(now));
		String stuName = form.getStuName();
		if(StringUtils.hasText(stuName)){
			rules.add(Rule.property("student.cade.name").contain(stuName));
		}
		String enrollName = form.getEnrollName();
		if(StringUtils.hasText(enrollName)){
			rules.add(Rule.property("enroll.name").contain(enrollName));
		}
		TbClass banji = form.getBanji();
		if(banji!=null){
			rules.add(Rule.property("student.banji.id").equal(banji.getId()));
		}
		return Rule.and(rules).toSpecification();
	}
	
	@RequestMapping(value="/participantPage")
	@ResponseBody
	public Object participantPage(String id,String sort){
		Sort sort1=new Sort(sort);
		List<TbParticipant> list=service.participantPage(UUID.fromString(id),sort1);
		return EasyuiResultBuilder.buildDataGridResult(list.size(), list);
	}
	
	@RequestMapping(value="/exportExcel",method=RequestMethod.GET)
	@ResponseBody
	public Object exportExcel(String enrollId,HttpServletRequest request,HttpServletResponse response) throws IOException{
		String[] excelHeader = { "班级","学号","姓名", "身份证号码","性别","民族","经手人","报名费"};
		HSSFWorkbook wb = new HSSFWorkbook();  
        HSSFSheet sheet = wb.createSheet("学生报名情况表");  
        HSSFRow row = sheet.createRow((int) 0);  
        HSSFCellStyle style = wb.createCellStyle();  
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        
        for(int i=0;i<excelHeader.length;i++){
        	HSSFCell cell=row.createCell(i);
        	cell.setCellValue(excelHeader[i]);
        	cell.setCellStyle(style);  
            sheet.setColumnWidth(i, 16*256); 
        }
		
        Sort sort=new Sort("creator.dept.sort","creator.sort","student.stuNo");
		List<TbParticipant> list=service.participantPage(UUID.fromString(enrollId), sort);
		for (int j = 0; j < list.size(); j++) {
			TbParticipant participant = list.get(j);
			row=sheet.createRow(j+1);
			HSSFCell cell=row.createCell(0);
			//cell.setCellStyle(style);
			cell.setCellValue(participant.getStudent().getBanji().getName());
			cell=row.createCell(1);
			//cell.setCellStyle(style);
			cell.setCellValue(participant.getStudent().getStuNo());
			cell=row.createCell(2);
			//cell.setCellStyle(style);
			cell.setCellValue(participant.getStudent().getName());
			cell=row.createCell(3);
			//cell.setCellStyle(style);
			cell.setCellValue(participant.getStudent().getIdNo());
			sheet.setColumnWidth(3, 20*256);
			cell=row.createCell(4);
			//cell.setCellStyle(style);
			cell.setCellValue(participant.getStudent().getSex());
			cell=row.createCell(5);
			//cell.setCellStyle(style);
			cell.setCellValue(participant.getStudent().getNation());
			cell=row.createCell(6);
			//cell.setCellStyle(style);
			cell.setCellValue(participant.getCreator().getName());
			cell=row.createCell(7);
			//cell.setCellStyle(style);
			cell.setCellValue(participant.getCost());
		}
		Enroll enroll=enrollService.getById(UUID.fromString(enrollId));
		String filename=enroll.getName()+"报名表.xls";
		filename=getStr(request, filename);
        response.setContentType("application/vnd.ms-excel");  
        response.setHeader("Content-disposition", "attachment;filename="+filename);  
        OutputStream ouputStream = response.getOutputStream();  
        wb.write(ouputStream);  
        ouputStream.flush();  
        ouputStream.close();
        wb.close();

		return null;
	}
	
    /****
     * 获取下载中文文件名的网络字符串
     * 
     * @param request
     *            请求对象
     * @param fileName
     *            文件名
     * @return
     */
    public String getStr(HttpServletRequest request, String fileName) {
        String downloadFileName = null;
        String agent = request.getHeader("USER-AGENT");
        try {
            if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
                downloadFileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
            } else {
                downloadFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return downloadFileName;
    }

}
